<?php
/**
 * Module ClickCounter
 *
 * @author develx
 */
class ClickCounter extends Module {
    protected $name = 'ClickCounter';
    protected $administrable = true;
    protected $version = '2010-08-23';
    protected $details = array('dependencies' => array(),
            'observes' => array('ClickCounter'));

    const CLICKS = 'clickCounter';

    protected $clicksTable = array('url' => "v'512'PN", 'clicks' => 'iN');

    protected $clickRecord = array('table' => self::CLICKS, 'data' => array());

    public function __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
        $this->clickRecord['properties'] = $this->clicksTable;
    }

    public function install() {
        Modules::getModule('Users')->registerRights($this->getName(),
                $this->getRights());
        return $this->dbdriver->createTable(self::CLICKS, $this->clicksTable);
    }

    public function uninstall() {
        return $this->dbdriver->dropTable(self::CLICKS);
    }

    public function onClick(&$details, $source) {
        $cols = array('clicks');
        $check = &$this->dbdriver->select(self::CLICKS, $cols, '`url` = \'' .
                $this->dbdriver->escapeString($details) . '\'');
        if (isset($check[0])) {
            $update = array('clicks' => $check[0]['clicks'] + 1);
            $this->dbdriver->update(self::CLICKS, $update, '`url` = \'' .
                    $this->dbdriver->escapeString($details) . '\'');
        } else {
            $click = $this->clickRecord;
            $click['data'] = array('url' => $details, 'clicks' => 1);
            $this->dbapi->save($click);
        }
        Kernel::setRedirect($details);
    }

    public function  displayBlank($param = null) {
        echo $this->getLink(urlencode(urlencode($param)), 'click');
    }

    public function displayAdminIndex() {
        $cols = array('url', 'clicks');
        $urls = &$this->dbdriver->select(self::CLICKS, $cols);
        $params = array('urls' => &$urls);
        $this->template('list', $params);
    }

    public function displayAdminSubmenu() {}
}
?>
